//
//  DMDetailViewController.m
//  TwitterFon
//
//  Created by kaz on 11/30/08.
//  Copyright 2008 naan studio. All rights reserved.
//

#import <QuartzCore/QuartzCore.h>
#import "GuaziAppDelegate.h"
#import "DMDetailViewController.h"
#import "FriendDetailViewController.h"
#import "UserTimelineController.h"
#import "ColorUtils.h"
#import "TwoButtonsCell.h"
#import "CardSelectViewController.h"

static NSString* sUserDetailText[2] = {
    @"TA的动态",
    @"TA的个人资料",
};

static NSString* sYourDetailText[2] = {
    @"我发表的动态",
    @"我的个人资料",
};

#define NUM_SECTIONS 3
#define kTagAccept 101
#define kTagReject 102

enum {
    SECTION_MESSAGE,
    SECTION_MORE_ACTIONS,
    SECTION_DELETE,
};

enum {
    ROW_USER_TIMELINE,
    ROW_PROFILE,
};

@interface NSObject (UserViewControllerDelegate)
- (void)removeMessage:(DirectMessage*)message;
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRequestAction:(NSIndexPath *)indexPath;
@end

@implementation DMDetailViewController

#pragma mark - init & destroy

- (id)initWithMessage:(DirectMessage*)value
{
    self = [super initWithStyle:UITableViewStyleGrouped];

    userView    = [[UserView alloc] initWithFrame:CGRectMake(0, 0, 320, 387)];
    deleteCell  = [[DeleteButtonCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"DeleteCell"];
    messageCell = [[DMDetailCell alloc] initWithMessage:value];
    
    message = value;
    [userView setUser:message.sender];
    
    self.title = message.sender.screenName;
    
    if ([GuaziAppDelegate isMyScreenName:message.sender.screenName]) {
        isOwnMessage = true;
    }
    else {
        UIBarButtonItem *button = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemReply target:self action:@selector(postTweet:)] autorelease]; 
        self.navigationItem.rightBarButtonItem = button;        
    }
    
	return self;
}


- (void)dealloc {
    [messageCell release];
    [deleteCell release];
    [userView release];
    [super dealloc];
}


#pragma mark - 生命周期方法

- (void)viewWillAppear:(BOOL)animated 
{
    if ( [kDMCodeAskCard compare:message.appendCode] == NSOrderedSame ) {
        cardActionView = [[CardActionView alloc] initWithFrame:CGRectMake(0, 0, 320, 60)];
        cardActionView.message = message;
    }
    else {
        cardActionView = nil;
    }
    
    [super viewWillAppear:animated];
    //self.navigationController.navigationBar.tintColor = nil;
}


- (void) viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self.tableView reloadData];
}


- (void)viewDidDisappear:(BOOL)animated
{
    if (twitterClient) {
        [twitterClient cancel];
        [twitterClient release];
        twitterClient = nil;
    }
}


#pragma mark - TableView Datasource Delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{
    if ( [kDMCodeAskCard compare:message.appendCode] == NSOrderedSame ) {
        return NUM_SECTIONS + 1;
    }
    else {
        return NUM_SECTIONS;
    }
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{
    if ( section == 0 ) {
        return 1;
    }
    else if ( section == 1 ) {
        return 2;
    }
    else if ( section == 2 ) {
        return 1;
    }
    
    return 0;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == SECTION_MESSAGE) {
        return messageCell.cellHeight;
    }
    else {
        return 44;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
    BOOL messageAction = NO;
    BOOL requestActions = NO;
    BOOL moreActions = NO;
    BOOL deleteAction = NO;
    
    /*if ( [kDMCodeAskCard compare:message.appendCode] == NSOrderedSame ) {
        if ( indexPath.section == 0 ) {
            messageAction = YES;
        }
        else if ( indexPath.section == 1 ) {
            requestActions = YES;
        }
        else if ( indexPath.section == 2 ) {
            moreActions = YES;
        }
        else if ( indexPath.section == 3 ) {
            deleteAction = YES;
        }
    }
    else {
        if ( indexPath.section == 0 ) {
            messageAction = YES;
        }
        else if ( indexPath.section == 1 ) {
            moreActions = YES;
        }
        else if ( indexPath.section == 2 ) {
            deleteAction = YES;
        }
    }*/
    
    if ( indexPath.section == 0 ) {
        messageAction = YES;
    }
    else if ( indexPath.section == 1 ) {
        moreActions = YES;
    }
    else if ( indexPath.section == 2 ) {
        deleteAction = YES;
    }
    
    if ( messageAction ) {
        return messageCell;
    }
    else if ( requestActions ) {
        return [self tableView:tableView cellForRequestAction:indexPath];
    }
    else if ( moreActions ) {
        static NSString *CellIdentifier = @"UserViewCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
        }
        
        cell.textLabel.textAlignment = UITextAlignmentCenter;
        cell.textLabel.textColor = [UIColor cellLabelColor];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.textLabel.text = (isOwnMessage) ? sYourDetailText[indexPath.row] : sUserDetailText[indexPath.row];
        return cell;
    }
    else if ( deleteAction ) {
        [deleteCell setTitle:@"删除本条消息"];
        return deleteCell;
    }
    
    return nil;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRequestAction:(NSIndexPath *)indexPath 
{
    if ( [kDMCodeAskCard compare:message.appendCode] == NSOrderedSame ) {
        if ( [GuaziAppDelegate getAppDelegate].user.userId == message.senderId ) {
            //发送的请求
            UITableViewCell* cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"requestResultCell"] autorelease];
            cell.textLabel.text = @"请求结果";
            return cell;
        }
        else {
            TwoButtonsCell* cell = [[[TwoButtonsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"requestButtonCell"] autorelease];
            cell.button1.tag = kTagAccept;
            cell.button2.tag = kTagReject;
            [cell setDelegate:self];
            cell.backgroundColor = [UIColor groupTableViewBackgroundColor];
            
            return cell;
        }
    }
    
    return nil;
}


#pragma mark - TableView Delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:TRUE];
    
    switch (indexPath.section) {
        case SECTION_MESSAGE:
            break;
        case SECTION_MORE_ACTIONS:
            if (indexPath.row == ROW_USER_TIMELINE) {
                UserTimelineController* userTimeline = [[[UserTimelineController alloc] initWithUser:message.sender] autorelease];
                [self.navigationController pushViewController:userTimeline animated:true];
            }
            else if (indexPath.row == ROW_PROFILE) {
                FriendDetailViewController *profile = [[[FriendDetailViewController alloc] initWithUser:message.sender] autorelease];
                [self.navigationController pushViewController:profile animated:true];
            }
            break;
            
        case SECTION_DELETE:
        {
            UIActionSheet *as = [[UIActionSheet alloc] initWithTitle:nil
                                                            delegate:self
                                                   cancelButtonTitle:@"取消"
                                              destructiveButtonTitle:@"删除本条消息"
                                                   otherButtonTitles:nil];
            [as showInView:self.navigationController.parentViewController.view];
            [as release];
        }
        break;
            
        default:
            break;
    }

}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == SECTION_MESSAGE) {
        return userView;
    }
    else {
        return nil;
    }
}


- (UIView*) tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if ( [kDMCodeAskCard compare:message.appendCode] == NSOrderedSame ) {
        if ( section == 0 ) {
            return cardActionView;
        }
    }
    
    return nil;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == SECTION_MESSAGE) {
        return 80;
    }
    else {
        return 0;
    }
}


- (CGFloat) tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if ( [kDMCodeAskCard compare:message.appendCode] == NSOrderedSame ) {
        if ( section == 0 ) {
            return 50;
        }
    }
    
    return 0;
}


#pragma mark - 实际操作方法s

- (void)postTweet:(id)sender
{
    GuaziAppDelegate *appDelegate = [GuaziAppDelegate getAppDelegate];
    PostViewController* postView = appDelegate.postView;
    
    [postView editDirectMessage:message.sender.screenName];
}


- (void) acceptAskCard
{
    CardSelectViewController* controller = [[CardSelectViewController alloc] initWithStyle:UITableViewStylePlain];
    controller.message = message;
    [self.navigationController pushViewController:controller animated:YES];
    [controller release];
}


- (void) rejectAskCard
{
    BOOL result = [TwitterClient rejectAskCardSync:[message askId] dmId:message.messageId message:@""];
    if ( result ) {
        message.appendResult = kDMResultCardReject;
        [self.tableView reloadData];
    }
}


- (void)actionSheet:(UIActionSheet *)as clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (as.cancelButtonIndex == buttonIndex) {
        return;
    }

    // Delete message
    //
    TwitterClient* client = [[TwitterClient alloc] initWithTarget:[GuaziAppDelegate getAppDelegate]
                                                           action:@selector(messageDidDelete:obj:)];
    client.context = [message retain];
    [client destroy:message];

    [self.navigationController popViewControllerAnimated:true];
}


#pragma mark - ButtonCell Delegate

- (NSString*) titleForButton:(NSInteger)tag
{
    if ( [kDMCodeAskCard compare:message.appendCode] == NSOrderedSame ) {
        if ( tag == kTagAccept ) {
            return @"同意";
        }
        else {
            return @"拒绝";
        }
    }
    else {
        return @"";
    }
}


- (UIImage*) imageForButton:(NSInteger)tag
{
    if ( [kDMCodeAskCard compare:message.appendCode] == NSOrderedSame ) {
        if ( tag == kTagAccept ) {
            return [[UIImage imageNamed:@"button_green.png"] stretchableImageWithLeftCapWidth:7 topCapHeight:0];
        }
        else {
            return [[UIImage imageNamed:@"deleteButton.png"] stretchableImageWithLeftCapWidth:7 topCapHeight:0];
        }
    }
    else {
        return nil;
    }
}


- (BOOL) enabledForButton:(NSInteger)tag
{
    return YES;
}


- (void) didClickButton:(NSInteger)tag withObject:(id)object
{
    if ( [kDMCodeAskCard compare:message.appendCode] == NSOrderedSame ) {
        if ( tag == kTagAccept ) {
        }
        else {
        }
    }
}


@end

